import axios, {AxiosResponse, InternalAxiosRequestConfig, AxiosError} from 'axios'
import {ResultEnum} from "@/enums/httpEnum"
import {ErrorPageNameMap} from "@/enums/pageEnum"
import {MessageError, redirectErrorPage} from '@/utils'

const axiosInstance = axios.create({
    baseURL: import.meta.env.DEV ? import.meta.env.VITE_DEV_PATH : import.meta.env.VITE_PRO_PATH,
    timeout: ResultEnum.TIMEOUT,
})

axiosInstance.interceptors.request.use(
    (config: InternalAxiosRequestConfig) => {
        return config
    },
    (error: AxiosError) => {
        Promise.reject(error)
    }
)

// 响应拦截器
axiosInstance.interceptors.response.use(
    (res: AxiosResponse) => {
        const {code} = res.data as { code: number }
        if (code === undefined || code === null) return Promise.resolve(res.data)
        if (code === ResultEnum.DATA_SUCCESS) return Promise.resolve(res.data)
        // 重定向
        if (ErrorPageNameMap.get(code)) redirectErrorPage(code)
        return Promise.resolve(res.data)
    },
    (err: AxiosResponse) => {
        Promise.reject(err)
        const url = err.config.url;
        MessageError("请求地址：" + url + " ；异常原因：" + err?.response?.data?.ExceptionMessage, {duration: 10000})
    }
)

export default axiosInstance
